<?php

namespace app\common\model;

use app\common\BaseModel;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;
use think\Exception;
use think\Model;

class Product extends BaseModel
{

    const DISABLED_AMOUNT_SCHEME = 0;
    const ENABLED_AMOUNT_SCHEME = 1;

    public static $fieldTypes = [
        'id' => 'number',
        'aid' => 'number',
        'cate_id' => 'number',
        'status' => 'number',
        'is_deleted' => 'number',
        'format' => 'string',
        'product_name' => 'string',
        'created_at' => 'date',
        'pic_url' => 'string',
        'proxy' => 'string',
        'sex' => 'string',
        'flag' => 'string',
        'description' => 'string',
        'amount_scheme' => 'number',
    ];

    public function manager()
    {
        return $this->belongsTo(AdminUser::class);
    }

    public function category()
    {
        return $this->hasOne(ProductCategory::class);
    }

    public static function saveData($data)
    {
        if(empty($data['id'])) {
            if(self::findProductName($data['product_name'])) {
                throw new Exception('商品不能重复');
            }

            if(!ProductCategory::findById($data['cate_id'])) {
                throw new Exception('商品分类不存在或已删除');
            }

            if(!empty($data['pic_url'])) {
                if(!file_exists(public_path() .'storage/'. $data['pic_url'])) {
                    throw new Exception('商品分类图片不存在');
                }
            }

            if(!empty($data['start_time']) && !empty($data['end_time'])) {
                if(strtotime($data['start_time']) > strtotime($data['end_time'])) {
                    throw new Exception('计划开始时间必须小于等于计划结束时间');
                }
            }

            if(isset($data['limit_num']) && $data['limit_num'] > 0) {
                if(isset($data['amount'])) {
                    if($data['limit_num'] > $data['amount']) {
                        throw new Exception('限定商品数量必须小于等于商品数量');
                    }
                }

                $data['remain_num'] = $data['limit_num'];
            }else{
                $data['remain_num'] = !empty($data['amount']) ? $data['amount'] : 0;
            }

            $insData = [
                'aid' => request()->user['user_id'],
                'cate_id' => $data['cate_id'],
                'price' => $data['price'],
                'format' => $data['format'],
                'pic_url' => !empty($data['pic_url']) ? $data['pic_url'] : '',
                'remark' => !empty($data['remark']) ? $data['remark'] : '',
                'product_name' => $data['product_name'],
                'flag' => !empty($data['flag']) ? $data['flag'] : '',
                'sex' => !empty($data['sex']) ? $data['sex'] : '',
                'description' => !empty($data['description']) ? $data['description'] : '',
                'proxy' => !empty($data['proxy']) ? $data['proxy'] : '',
                'amount' => !empty($data['amount']) ? $data['amount'] : 0,
                'amount_scheme' => !empty($data['amount_scheme']) ? $data['amount_scheme'] : 0,
                'rand_num' => !empty($data['rand_num']) ? $data['rand_num'] : 1,
                'limit_num' => !empty($data['limit_num']) ? $data['limit_num'] : 0,
                'remain_num' => $data['remain_num'],
            ];

            if(!empty($data['start_time'])) {
                $insData['start_time'] = $data['start_time'];
            }

            if(!empty($data['end_time'])) {
                $insData['end_time'] = $data['end_time'];
            }

            self::insertGetId($insData);
        }else{
            if(!$modelRecord = self::findById($data['id'])) {
                throw new Exception('商品不存在或已删除');
            }

            if(!empty($data['product_name'])) {
                if($modelRecord->product_name != $data['product_name']) {
                    if(self::findProductName($data['product_name'])) {
                        throw new Exception('商品名称不能重复');
                    }
                }

                $modelRecord->product_name = $data['product_name'];
            }

            if(!empty($data['cate_id'])) {
                if(!ProductCategory::findById($data['cate_id'])) {
                    throw new Exception('商品分类不存在或已删除');
                }

                $modelRecord->cate_id = $data['cate_id'];
            }

            if(!empty($data['start_time']) && !empty($data['end_time'])) {
                if(strtotime($data['start_time']) > strtotime($data['end_time'])) {
                    throw new Exception('计划开始时间必须小于等于计划结束时间');
                }
            }

            if(!empty($data['start_time']) && !empty($modelRecord->end_time)) {
                if(strtotime($modelRecord->end_time) < strtotime($data['start_time'])) {
                    throw new Exception('计划开始时间必须小于等于计划结束时间');
                }
            }

            if(!empty($data['end_time']) && !empty($modelRecord->start_time)) {
                if(strtotime($modelRecord->start_time) > strtotime($data['end_time'])) {
                    throw new Exception('计划结束时间必须大于计划开始时间');
                }
            }

            if(isset($data['limit_num']) && $data['limit_num'] > 0) {
                if(isset($data['amount'])) {
                    if($data['limit_num'] > $data['amount']) {
                        throw new Exception('限定商品数量必须小于等于商品数量');
                    }
                }else{
                    if(isset($modelRecord->amount) && $data['limit_num'] > $modelRecord->amount) {
                        throw new Exception('限定商品数量必须小于等于商品数量');
                    }
                }

                $modelRecord->limit_num = $data['limit_num'];
                $modelRecord->remain_num = $data['limit_num'];
            }else{
                $modelRecord->remain_num = !empty($data['amount']) ? $data['amount'] : $modelRecord->remain_num;
            }

            if(!empty($data['pic_url'])) {
                if(!file_exists(public_path() . 'storage/' . $data['pic_url'])) {
                    throw new Exception('商品图片不存在');
                }

                $modelRecord->pic_url = $data['pic_url'];
            }

            if(isset($data['status'])) $modelRecord->status = $data['status'];
            if(!empty($data['flag'])) $modelRecord->flag = $data['flag'];
            if(!empty($data['sex'])) $modelRecord->sex = $data['sex'];
            if(!empty($data['description'])) $modelRecord->description = $data['description'];
            if(!empty($data['proxy'])) $modelRecord->proxy = $data['proxy'];
            if(!empty($data['amount'])) $modelRecord->amount = intval($data['amount']);
            if(!empty($data['format'])) $modelRecord->format = $data['format'];
            if(!empty($data['remark'])) $modelRecord->remark = $data['remark'];
            if(isset($data['amount_scheme'])) $modelRecord->amount_scheme = $data['amount_scheme'];
            if(isset($data['rand_num'])) $modelRecord->rand_num = $data['rand_num'];
            if(isset($data['start_time'])) $modelRecord->start_time = !empty($data['start_time']) ? $data['start_time'] : null;
            if(isset($data['end_time'])) $modelRecord->end_time = !empty($data['end_time']) ? $data['end_time'] : null;

            $modelRecord->save();
        }
    }

    /**
     * 根据商品名称查询
     * @param $productName
     * @return BaseModel|array|mixed|Model|null
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public static function findProductName($productName)
    {
        return self::findNoDeleted(['product_name' => $productName]);
    }

}